require "Net/chatHandler"

UIChatPanel = {};
HelperFunc.SetUIEnv(UIChatPanel)
local this = UIChatPanel;

this.clickPos = nil;
this.btn_world = nil;
this.btn_city = nil;
this.btn_system = nil;
this.btn_other = nil
this.btn_private = nil;
this.btn_InvasionTeam=nil
this.teamCtrl=nil

this.privateRedPoint = nil;
this.btn_return = nil;
this.btn_close = nil;
this.emotionList = nil;
this.friendList = nil;
this.messageInfo = nil;
this.listCtrl = nil;
this.emotionCtrl = nil;
this.btnCtrl = nil;
this.btnBarrage=nil
---@type FairyGUI.GRichTextField
this.inputText = nil;
this.btn_send = nil;
this.btn_emotion = nil;
this.curChannel = Config.MsgChannel.World;
this.lastSendTimeChannel = {};
local cdTime = G.dataTable["t_global"]["43"].f_int_value/1000;
this.limitTime = {
    [1] = cdTime,
    [2] = cdTime,
    [3] = cdTime,
    [4] = cdTime,
    [5] = cdTime,
    [9] = cdTime,
}
this.curPrivateData = {};     --当前私聊对象的数据
this.PrivateList = {};
this.msgInfo = {};

this.isFriendList = true;
this.isfirst = true;
this.myPlayerId = 0
this.showEmotion = false;
local currentServer;
local currentChannel;
local changeChannel = nil;
local pnlChannel;
local btnBackToChat;
local chdynamicList;
local isCityInLBS = false
---@type LBSRoom[]
local ChatChList = {};
function UIChatPanel.Init(_type, _isOnlyGuildBattle,isInvasionTeam)
    this.isInvasionTeam=isInvasionTeam
    this.curChannel = _type or Config.MsgChannel.World;
    this.isOnlyGuildBattle = _isOnlyGuildBattle;
    local name, packageName = getUIName(PanelNames.UIChatPanel);
    panelMgr:Push(name, packageName, this.onCreate, Config.useLocalUI);
end

--定义控件
---@param obj GComponent
function UIChatPanel.onCreate(obj)
    if not UIPackage.GetById("FUI/Emoji") then
        this.isNeedRemovePackage = true;
        AddUIPackageDepend(PanelNames.UIChatPanel, "FUI/Emoji")
    end
    --chatHandler.mychatChannel[Config.MsgChannel.World] = "world-room-".. AppConst.ServerId .. "/room-1"
    --chatHandler.mychatChannel[Config.MsgChannel.System] = "chat-world-uzone"

    clickPos = obj:GetChild("bgClose");
    btn_world = obj:GetChild("btn_world");
    btn_city = obj:GetChild("btn_city");
    btn_system = obj:GetChild("btn_system");
    btn_other = obj:GetChild("btn_other");
    btn_private = obj:GetChild("btn_chat");
    btn_InvasionTeam=obj:GetChild("btn_team")

    this.btn_guild = obj:GetChild("btn_guild")
    privateRedPoint = obj:GetChild("privateRedPoint");
    privateRedPoint.visible = false
    btn_emotion = obj:GetChild("emotionBtn");
    inputText = obj:GetChild("InputText");
    btn_send = obj:GetChild("sendBtn");
    btn_return = obj:GetChild("backBtn");
    btn_close = obj:GetChild("closeBtn");
    emotionList = obj:GetChild("emotionList");
    friendList = obj:GetChild("friendList");
    friendList:SetVirtual()
    messageInfo = obj:GetChild("messageInfo"):GetChild("messageInfo");
    messageInfo:SetVirtual()

    teamCtrl=obj:GetController("Teams")
    listCtrl = obj:GetController("listCtrl");
    emotionCtrl = obj:GetController("emotionCtrl");
    btnCtrl = obj:GetController("btnCtrl");
    btnBarrage=obj:GetChild("btn_barrage")
    pnlChannel = obj:GetController("pnlChannel");
    currentServer = obj:GetChild("currentServer");
    this.ctrlServer = currentServer:GetController("channel")
    currentChannel = obj:GetChild("currentChannel");
    --changeChannel=obj:GetChild("changeChannel");
    chdynamicList = obj:GetChild("listChannel")
    btnBackToChat = obj:GetChild("btnBackToChat");
    btnListCtrl = obj:GetController("btnListCtrl");
    this.stateController = obj:GetController("state")
    if this.isOnlyGuildBattle then
        this.stateController.selectedIndex = 1;
    else
        this.stateController.selectedIndex = 0;
    end
    if this.isInvasionTeam then
        teamCtrl.selectedIndex=1
        this.InitBarrage()
    else
        teamCtrl.selectedIndex=0
    end
    this.ctrlNewMessage = obj:GetController("newMessage")
    this.numMessageText = obj:GetChild("numMessage")
    this.messageInfoSystem = obj:GetChild("messageInfoSystem")
    chdynamicList.itemRenderer = this.ShowCh;
    chdynamicList:SetVirtual()
    this.messageInfoSystem.itemRenderer = this.SystemItemRender
    this.messageInfoSystem:SetVirtual()
    listCtrl.selectedIndex = 0;
    emotionCtrl.selectedIndex = 0;
    this.ChatPageMapping();
    btnCtrl.selectedIndex = 1;
    btnListCtrl.selectedIndex = this.pageMapping[curChannel];
    this.btnIndex = 1
    showEmotion = false;
    this.emotionDataList = logicMgr.ChatManager.LoadEmoji()
    logicMgr.ChatManager.LoadAllMsgFromFile()
    --this.freshReceiveMsg();
    this.addEvent();
    --this.onClickWorld();
    this.lastChatItem = nil
    myPlayerId = logicMgr.HeroManager.GetRoleInfo().playerId
    --UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. btn_city.name, btn_city, Config.RedDotsType.Chat,Config.MsgChannel.Server);
    --UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. btn_world.name, btn_world, Config.RedDotsType.Chat,Config.MsgChannel.World);
    UIRedDots.addViewListen(PanelNames.UIChatPanel, "UIChatPanel" .. btn_private.name, btn_private, Config.RedDotsType.Chat, Config.MsgChannel.Person);
    --UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. btn_system.name, btn_system, Config.RedDotsType.Chat,Config.MsgChannel.System);
    --UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. btn_city.name, btn_city, Config.RedDotsType.Chat,Config.MsgChannel.Server);
    UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. this.btn_guild.name, this.btn_guild, Config.RedDotsType.Chat,Config.MsgChannel.Guild);
    logicMgr.LBSManager.AutoJoinRoom()
    this.InitLBSServer()
    this.RefreshServer()
    SDKManager.ReqMyselfUserInfo()
end
function UIChatPanel.InitBarrage()
    this.isShowBarrage=GetPlayerPrefs("IsInvasionChatShowBarrage")
    --0开启，1,关闭
    if this.isShowBarrage~=nil then
        this.isShowBarrage=tonumber(this.isShowBarrage)
    else
        this.isShowBarrage=0
    end
    this.btnBarrage.onClick:Clear()
    local stateCtrl=this.btnBarrage:GetController("button")
    stateCtrl.selectedIndex=this.isShowBarrage
    this.btnBarrage.onClick:Add(function()
        if this.isShowBarrage==0 then
            FireEvent(Config.EventType.InvasionChangeBulletState,false)
            this.isShowBarrage=1
            stateCtrl.selectedIndex=1
        else
            FireEvent(Config.EventType.InvasionChangeBulletState,true)
            this.isShowBarrage=0
            stateCtrl.selectedIndex=0
        end
        SetPlayerPrefs("IsInvasionChatShowBarrage",this.isShowBarrage)
    end)
end

function UIChatPanel.ChatPageMapping()
    this.pageMapping = {}
    this.pageMapping[Config.MsgChannel.LBS] = 0
    this.pageMapping[Config.MsgChannel.Server] = 0
    this.pageMapping[Config.MsgChannel.World] = 1
    this.pageMapping[Config.MsgChannel.Person] = 2
    this.pageMapping[Config.MsgChannel.System] = 3
    this.pageMapping[Config.MsgChannel.Guild] = 5
    this.pageMapping[Config.MsgChannel.InvasionTeam]=0
end
function UIChatPanel.addEvent()
    btn_world.onClick:Add(this.onClickWorld)
    btn_city.onClick:Add(this.onClickCity)
    btn_system.onClick:Add(this.onClickSystem)
    btn_other.onClick:Add(this.onClickOther)
    btn_private.onClick:Add(this.onClickPrivate)
    this.btn_guild.onClick:Add(this.onClickGuild)
    btn_InvasionTeam.onClick:Add(this.onClickInvasionTeam)
    currentServer.onClick:Add(this.OncurrentServer)
    currentChannel.onClick:Add(this.OnChangeChannel)
    --changeChannel.onClick:Add(this.OnchangeChannel)
    btnBackToChat.onClick:Add(this.OnBtnBackToChat)

    btn_send.onClick:Add(this.onClickSendMsg)
    btn_emotion.onClick:Add(this.onClickEmotion)
    btn_return.onClick:Add(this.onClickReturn)
    btn_close.onClick:Add(this.onCloseClick)
    clickPos.onClick:Add(this.onCloseClick)
    this.ctrlServer.onChanged:Add(this.OnClickServer)
    this.inputText.onFocusOut:Add(this.OnFocusOutInput)
end

function UIChatPanel.removeEvent()
    btn_world.onClick:Remove(this.onClickWorld)
    btn_city.onClick:Remove(this.onClickCity)
    btn_system.onClick:Remove(this.onClickSystem)
    btn_other.onClick:Remove(this.onClickOther)
    btn_private.onClick:Remove(this.onClickPrivate)
    btn_InvasionTeam.onClick:Remove(this.onClickInvasionTeam)
    this.btn_guild.onClick:Remove(this.onClickGuild)
    currentServer.onClick:Remove(this.OncurrentServer)
    currentChannel.onClick:Remove(this.onClickSystem)
    btnBackToChat.onClick:Remove(this.onClickPrivate)

    btn_send.onClick:Remove(this.onClickSendMsg)
    btn_emotion.onClick:Remove(this.onClickEmotion)
    btn_return.onClick:Remove(this.onClickReturn)
    btn_close.onClick:Remove(this.onCloseClick)
    clickPos.onClick:Remove(this.onCloseClick)
    this.inputText.onFocusOut:Remove(this.OnFocusOutInput)

end

function UIChatPanel.listernEvent()
    ListenEvent(Config.EventType.Fresh_Chat, this.Fresh_ChatByMsg);
    ListenEvent(Config.EventType.FreashRoleInfoOther, this.GotOtherShowInfo)
    ListenEvent(Config.EventType.CityRoomJoinSuc, this.CityRoomJoinSuc)

end

function UIChatPanel.GotOtherShowInfo(info)
    showUI(PanelNames.UIPlayerShow, info,nil,false,function ()
        UIBottom.onSetTown();
    end)
end

function UIChatPanel.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_Chat, this.Fresh_ChatByMsg);
    CloseEvent(Config.EventType.FreashRoleInfoOther, this.GotOtherShowInfo)
    CloseEvent(Config.EventType.CityRoomJoinSuc, this.CityRoomJoinSuc)

    UIRedDots.removeViewEvent(PanelNames.UIChatPanel);

    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIChatPanel);
end

function UIChatPanel.OnDestroy()
    this.removeEvent();
    this.lastChatItem = nil

    if this.isNeedRemovePackage and UIPackage.GetById("FUI/Emoji") then
        UIPackage.RemovePackage("FUI/Emoji")
    end
end

function UIChatPanel.OnEnable()
    this.worldOpen = FuncOpenManager.isOpen(Config.FuncOpenType.WorldChat)
    this.cityOpen = FuncOpenManager.isOpen(Config.FuncOpenType.CityChat)

    this.listernEvent();
end

function UIChatPanel.OnDisable()

    logicMgr.ChatManager.setPrivateMsgInFile();
    this.LocalCloseEvent();
    FireEvent(Config.EventType.Fresh_Chat);
end

--控制界面显示
function UIChatPanel.playSpine()
end
------------------------Btn--------------------
function UIChatPanel.onClickWorld()
    --世界聊天
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.WorldChat, true, btn_world) then

    end
    listCtrl.selectedIndex = 0

    if curChannel == Config.MsgChannel.Person and not isFriendList then
        isFriendList = true;
        logicMgr.ChatManager.refreshMsgRead(curPrivateData["roleId"]);
    end
    if isfirst then
        isfirst = false;
    else
        this.playSpine();
    end
    curChannel = Config.MsgChannel.World;
    this.freshReceiveMsg(true);
    curPrivateData = {};
    if this.isInvasionTeam then
        btnBarrage.visible = false
    end
end

function UIChatPanel.onClickCity()
    --切换到主城聊天
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.CityChat, true, btn_city) then

    end
    if isCityInLBS then
        curChannel = Config.MsgChannel.LBS
    else
        curChannel = Config.MsgChannel.Server
    end
    listCtrl.selectedIndex = 0;
    this.freshReceiveMsg(true);
    curPrivateData = {};
    if this.isInvasionTeam then
        btnBarrage.visible = false
    end
end

function UIChatPanel.onClickSystem()
    --系统聊天
    curChannel = Config.MsgChannel.System;
    this.freshReceiveMsg(true);
    curPrivateData = {};
    listCtrl.selectedIndex = 0;
    if this.isInvasionTeam then
        btnBarrage.visible = false
    end
end

function UIChatPanel.onClickOther()
    UISysTips.AddMsg("暂未开放");
    if curChannel == Config.MsgChannel.World then
        btnListCtrl.selectedPage = "world";
    else
        btnListCtrl.selectedPage = "private";
    end
    return ;

    --[[    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.DrawChat,true) then
            return;
        end
        listCtrl.selectedPage = "msgList";
        UISysTips.AddMsg("暂未开放");
        return;]]
end
--公会
function UIChatPanel.onClickGuild()
    if logicMgr.GuildManager.getUnionId() == 0 then
        btnListCtrl.selectedIndex = this.pageMapping[curChannel];
        UISysTips.AddMsg(getLanguage("GuildInvestment_1114"))
        return
    end
    curChannel = Config.MsgChannel.Guild;
    this.freshReceiveMsg(true);
    curPrivateData = {};
    listCtrl.selectedIndex = 0;
    if this.isInvasionTeam then
        btnBarrage.visible = false
    end
end
--天灾队伍
function UIChatPanel.onClickInvasionTeam()
    curChannel = Config.MsgChannel.InvasionTeam;
    this.freshReceiveMsg(true);
    curPrivateData = {};
    if this.isInvasionTeam then
        btnBarrage.visible = true
    end
end
function UIChatPanel.onClickPrivate(showFriend, backBtnClick)
    --私聊
    if not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.PrivateChat, true, btn_private) then

    end
    if showFriend then
        isFriendList = true
    end
    if isFriendList then
        listCtrl.selectedIndex = 1;
        btnCtrl.selectedPage = "closeBtn";
        this.playSpine();
    else
        listCtrl.selectedIndex = 0;
        btnCtrl.selectedPage = "backBtn";
    end
    this.RefreshPrivateMsg(true, backBtnClick);
    logicMgr.ChatManager.HandlePrivateRed()
    if this.isInvasionTeam then
        btnBarrage.visible = false
    end
end

function UIChatPanel.OncurrentServer()
    --[[if(curChannel==Config.MsgChannel.World) then
        return;
    else
        curChannel = Config.MsgChannel.World;
        this.freshReceiveMsg();
        --UICity.IntoWorld();
    end]]
end

function UIChatPanel.OncurrentChannel()
    if (curChannel == Config.MsgChannel.LBS) then
        return ;
    else
        curChannel = Config.MsgChannel.LBS
        this.freshReceiveMsg(true);
        UICity.IntoLBS();
    end
end

function UIChatPanel.OnChangeChannel()
    chdynamicList.numItems = 0
    logicMgr.LBSManager.GetRooms(UIChatPanel.ShowChList)
end

function UIChatPanel.ShowChList()
    table.clear(ChatChList)
    for k, v in pairs(logicMgr.LBSManager.GetLBSRooms()) do
        table.insert(ChatChList, v)
    end
    local count = #ChatChList
    count = math.ceil(count / 2)
    chdynamicList.numItems = count;
end

function UIChatPanel.OnBtnBackToChat()
    pnlChannel.selectedIndex = 0;
end

function UIChatPanel.ShowCh(index, obj)
    index = index * 2 + 1
    this.ShowChItem(obj:GetChild("n0"), ChatChList[index])
    this.ShowChItem(obj:GetChild("n1"), ChatChList[index + 1])
end
function UIChatPanel.ShowChItem(obj, data)
    if data == nil then
        obj.visible = false
        return
    end
    obj.visible = true
    local chnametext = obj:GetChild("title");
    chnametext.text = data.name .. data.code
    local choose = obj:GetController("choose")
    if logicMgr.LBSManager.IsInRoom(data.channel) then
        choose.selectedIndex = 1
        this.selectChItemChoose = choose
    else
        choose.selectedIndex = 0
    end
    local s = obj:GetController("speed")
    if data.num <= 10 then
        s.selectedIndex = 0
    elseif data.num <= 15 then
        s.selectedIndex = 1
    else
        s.selectedIndex = 2
    end
    obj.onClick:Clear()
    obj.onClick:Add(function()
        if data.num >= 20 then
            UISysTips.AddMsg("频道人数满了")
            return
        end
        if data.channel == logicMgr.LBSManager.GetCurRoomChannel() then
            UISysTips.AddMsg("已经加入了该频道")
            return
        end
        --if this.selectChItemChoose then
        --     this.selectChItemChoose.selectedIndex = 0
        --end
        --choose.selectedIndex = 1
        -- this.selectChItemChoose = choose
        this.needShowJoinRoomTip = true
        logicMgr.LBSManager.ChangeRoom(data)
        this.OnBtnBackToChat()

    end)
end
---------------------发送消息------------------
function UIChatPanel.onClickSendMsg()
    if curChannel == Config.MsgChannel.World and not this.worldOpen then
        FuncOpenManager.isOpen(Config.FuncOpenType.WorldChat, true)
        return
    end

    if curChannel == Config.MsgChannel.Server and not this.cityOpen then
        FuncOpenManager.isOpen(Config.FuncOpenType.CityChat, true)
        return
    end

    local text = inputText.text;
    inputText.text = "";
    local originText = text
    local flag = true;
    text = string.gsub(text, "\r", "")
    text = string.gsub(text, "\n", "")
    for i = 1, string.len(text) do
        if string.sub(text, i, i) ~= ' ' then
            flag = false;
            break ;
        end
    end
    if flag then
        UISysTips.AddMsg(getLanguage("Sys_MsgInputEmpty"))--"输入不能为空")
        return ;
    end
    if string.match(text, "#cmd") ~= nil then
        local gm = string.sub(text, 6, #text);
        printError(gm)
        if Config.RemoteConfig.GoldenFinger == 1 then
            _G.gmcommand(gm);
        end
        return ;
    end
    if text == "#FPS" then
        Game.ShowFps = not Game.ShowFps;
        FireEvent(Config.EventType.Fresh_FPS, Game.ShowFps, 30);
        return ;
    end
    if text == "#8080" then
        showUI(PanelNames.UIDebug);
        UIDebug.showSelf();
        return ;
    end
    if curChannel == Config.MsgChannel.System then
        logError("系统页签不可发送消息")
        return
    end
    if curChannel == Config.MsgChannel.LBS then
        if not logicMgr.LBSManager.isSelectLBS then
            UISysTips.AddMsg("未加入该频道")
            return
        end
    end
    text = logicMgr.ChatManager.FilterUBB("color",text);
    text = logicMgr.ChatManager.FilterUBB("size",text);
    text = logicMgr.ChatManager.TransferEmojiKey(text)
    text = BlockWordFilter(text)
    local limitCount = dataTable.getDataTableByStringId("t_global",201,"f_int_value")
    text = string.limitstr(text,limitCount)
    local msgtbl = {};
    msgtbl.Channel = curChannel;
    msgtbl.Message = text
    msgtbl.serverId = Config.chatServerId;
    msgtbl.head = logicMgr.HeroManager.GetRoleHeadID();
    msgtbl.headFrame = HeroManager.GetRoleHeadFrame()
    local tempList = logicMgr.TitleManager.GetTitleData().showList
    msgtbl.titleId = tempList and tempList[1] or 0;
    --print("===head=====>"..msgtbl.head);
    msgtbl.level = logicMgr.HeroManager.GetRoleLevel();
    msgtbl.roleId = logicMgr.HeroManager.GetRoleId();
    msgtbl.roleName = logicMgr.HeroManager.GetRoleName();
    msgtbl.unRead = true;
    msgtbl.time = HelperFunc.GetServerTime(false);
    msgtbl.lbs = logicMgr.LBSManager.GetLocationName()
    msgtbl.unionName = logicMgr.GuildManager.getUnionName();

    if curChannel == Config.MsgChannel.World then
        if FuncOpenManager.isOpen(Config.FuncOpenType.WorldChat, true, btn_world) then
            if ChatManager.CheckMsg(curChannel, originText) then
                if IsWindowEditor() then
                    --chatHandler.broadCastMsg(chatHandler.mychatChannel[curChannel], msgtbl);
                    chatHandler.onRecChatMsg(msgtbl)
                else
                    SDKManager.SendTextMessageByWorld(text)
                end
                chatHandler.ReqChatInfo(1, text)
                this.ScrollToBottom()
            end
        end
    elseif curChannel == Config.MsgChannel.Guild then
        if FuncOpenManager.isOpen(Config.FuncOpenType.Guild, true, this.btn_guild) then
            if ChatManager.CheckMsg(curChannel, originText) then
                if IsWindowEditor() then
                    --chatHandler.broadCastMsg(chatHandler.mychatChannel[curChannel], msgtbl);
                    chatHandler.onRecChatMsg(msgtbl)
                else
                    SDKManager.SendTextMessageByGuild(text)
                end
                chatHandler.ReqChatInfo(4, text)
                this.ScrollToBottom()
            end
        end
    elseif curChannel ==Config.MsgChannel.InvasionTeam then
        MyLog("orginTex"..originText)
        if ChatManager.CheckMsg(curChannel,originText)then
            if IsWindowEditor() then
                --chatHandler.broadCastMsg(chatHandler.mychatChannel[curChannel], msgtbl);
                chatHandler.onRecChatMsg(msgtbl)
            else
                SDKManager.SendTextMessageByInvasion(text)
            end
            chatHandler.ReqChatInfo(5, text)
            this.ScrollToBottom()
        end
    elseif curChannel == Config.MsgChannel.Server then

        if FuncOpenManager.isOpen(Config.FuncOpenType.CityChat, true, btn_city) then
            if ChatManager.CheckMsg(curChannel, originText) then
                if IsWindowEditor() then
                    --chatHandler.broadCastMsg(chatHandler.mychatChannel[curChannel], msgtbl);
                    chatHandler.onRecChatMsg(msgtbl)
                else
                    SDKManager.SendTextMessageByCity(text)
                end
                chatHandler.ReqChatInfo(2, text)
                this.ScrollToBottom()
            end
        end
    elseif curChannel == Config.MsgChannel.Person then
        if FuncOpenManager.isOpen(Config.FuncOpenType.PrivateChat, true, btn_private) then
            if ChatManager.CheckMsg(curChannel) then
            if IsWindowEditor() then
                msgtbl.PlayerId = curPrivateData["roleId"];
                msgtbl.PlayerName = curPrivateData["roleName"];
                msgtbl.PlayerHead = curPrivateData["head"];
                chatHandler.sendPrivateMsg(curPrivateData["roleId"], msgtbl);
                chatHandler.sendPrivateMsg(logicMgr.HeroManager.GetRoleInfo().playerId, msgtbl);
                chatHandler.onRecChatMsg(msgtbl)
            else
                SDKManager.SendTextMessageByPrivate(text, curPrivateData["roleId"])
            end
            chatHandler.ReqChatInfo(3, text, curPrivateData["roleId"])
            this.ScrollToBottom()
        end
        logicMgr.ChatManager.refreshMsgRead(curPrivateData["roleId"]);
        end
    end
end

--------------------刷新消息内容----------------
function UIChatPanel.freshReceiveMsg(isBottom)
    msgInfo = {};
    this.refreshLastIndex = 0
    this.lastChatItem = nil

    if (curChannel == Config.MsgChannel.Person) then
        this.RefreshPrivateMsg(isBottom)
    else
        msgInfo = logicMgr.ChatManager.returnChatMsg(curChannel);
        if curChannel == Config.MsgChannel.System then
            this.messageInfoSystem.numItems = #msgInfo;
        else
            messageInfo.itemRenderer = this.setData;
            messageInfo.numItems = #msgInfo;
            this.RefreshShowNum()
        end
        MyLog("当前聊天频道"..curChannel.."队伍消息数量"..#msgInfo)
        if isBottom then
            this.ScrollToBottom()
        end
    end
    --UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. btn_city.name, btn_city, Config.RedDotsType.Chat,Config.MsgChannel.Server);
    --UIRedDots.addViewListen(PanelNames.UIChatPanel,"UIChatPanel" .. btn_world.name, btn_world, Config.RedDotsType.Chat,Config.MsgChannel.World);

end

function UIChatPanel.RefreshPrivateMsg(isBottom, backBtnClick)
    if isFriendList then
        PrivateList = logicMgr.ChatManager.returnSelfPrivateList();
        if #PrivateList == 0 then
            listCtrl.selectedPage = "msgList";
            btnListCtrl.selectedIndex = this.pageMapping[curChannel];
            if backBtnClick then
                this.onCloseClick()
            else
                UISysTips.AddMsg("您还没有好友聊天信息！")
            end

            return false;
        end
        friendList.itemRenderer = this.setFriendItem;
        friendList.numItems = #PrivateList;
    else
        this.refreshLastIndex = 0
        this.lastChatItem = nil
        msgInfo = logicMgr.ChatManager.GetPrivateMsgByTwoPlayer(curPrivateData["roleId"], myPlayerId);
        messageInfo.itemRenderer = this.setData;
        messageInfo.numItems = #msgInfo;
        if isBottom then
            this.ScrollToBottom()
        end
        this.RefreshShowNum()

    end
    curChannel = Config.MsgChannel.Person;
    btnListCtrl.selectedIndex = this.pageMapping[curChannel];
    return true
end
function UIChatPanel.RefreshShowNum()
    local count = 0
    for k, v in pairs(msgInfo) do
        if v.unRead then
            count = count + 1
        end
    end
    if count > 0 and count <= 30 then
        this.ctrlNewMessage.selectedIndex = 1
        this.numMessageText.text = tostring(count)
    elseif count > 30 then
        this.ctrlNewMessage.selectedIndex = 2
    else
        this.ctrlNewMessage.selectedIndex = 0
    end
end
function UIChatPanel.ScrollToBottom()
    messageInfo.scrollPane:ScrollBottom()
    if curChannel == Config.MsgChannel.Person then
        --logicMgr.ChatManager.refreshMsgRead(curChannel)
    else
        logicMgr.ChatManager.refreshMsgReadByChannel(curChannel)
    end

end
---------------------消息列表----------------------
function UIChatPanel.SystemItemRender(index, obj)
    index = index + 1
    local msgdata = msgInfo[index]
    if not msgdata then
        return
    end
    local text = obj:GetChild("systemDialog")
    text.text = msgdata.Message
end

local m_frame_mat = nil

function UIChatPanel.setData(index, obj)
    index = index + 1
    local msgdata = msgInfo[index];
    if not msgdata then
        return
    end

    local item = CtrlManager.GetCtrl(PanelNames.ChatMsgItem);
    if item ~= nil then
        item.initData(obj, msgdata, false);
    end

    if m_frame_mat == nil then
        m_frame_mat = Util.SetSkeletonAnimMatrialStencil(obj, 3)
    end

    local old = msgdata.unRead
    msgdata.unRead = false
    if old then
        logicMgr.ChatManager.HandleRedPoint(curChannel)
    end
    if this.refreshLastIndex <= index then
        this.refreshLastIndex = index
        this.lastChatItem = obj
        this.RefreshShowNum()
    end
end

---------------------私聊列表-----------------------
function UIChatPanel.setFriendItem(index, obj)
    local itemValue = PrivateList[index + 1];
    local mask = obj:GetChild("mask")
    local headIcon = obj:GetChild("head"):GetChild("HeadIcon")
    local frame = obj:GetChild("frame")
    local name = obj:GetChild("title")
    local msgNum = obj:GetChild("msgNum")
    local numCtrl = obj:GetController("numCtrl")
    numCtrl.selectedPage = "notShow";
    local playerModelId = itemValue["PlayerHead"];
    --print("====好友头像=====>"..playerModelId)
    local unReadNum = itemValue["unReadNum"];
    if unReadNum ~= nil and unReadNum ~= 0 then
        numCtrl.selectedPage = "show";
        msgNum.text = "消息数：" .. tostring(unReadNum);
    end
    name.text = itemValue["PlayerName"];
    if tonumber(playerModelId) ~= nil then
        headIcon.url = logicMgr.SkinManager.GetHeroIconBySkinId(itemValue["PlayerHead"])
    else
        headIcon.url = playerModelId
    end
    local friend = logicMgr.FriendManager.GetMyFriend(itemValue["PlayerId"])
    if friend then
        frame.url = "ui://ICONAtlas/" .. friend.picFrame
    end
    --headIcon.url = playerModelId--"ui://ICONAtlas/"..G.dataTable["t_hero"][tostring(playerModelId)].f_HeroIcon;
    --headIcon.url = "ui://ICONAtlas/"..playerModelId;

    obj.onClick:Add(function()
        curPrivateData["roleId"] = itemValue["PlayerId"];
        curPrivateData["roleName"] = itemValue["PlayerName"];
        curPrivateData["head"] = playerModelId;
        isFriendList = false;
        logicMgr.ChatManager.refreshMsgRead(curPrivateData["roleId"]);
        this.onClickPrivate();

    end);
end

-----------------进入私聊消息界面接口-------------
function UIChatPanel.PrivateChatMsgPort(data)
    --print("=====================>")
    --printTable(data);
    curPrivateData = data;
    isFriendList = false;
    logicMgr.ChatManager.refreshMsgRead(curPrivateData["roleId"]);
    this.onClickPrivate();
end

function UIChatPanel.onClickEmotion()
    if emotionCtrl.selectedIndex == 1 then
        -- emotionCtrl.selectedIndex = 1
        emotionList.itemRenderer = this.onClickEmoji;

        emotionList.numItems = #this.emotionDataList
        showEmotion = true;
        --else
        --emotionCtrl.selectedIndex = 0
        --    showEmotion = false;
    end
end

function UIChatPanel.onClickEmoji(index, obj)
    index = index + 1
    obj.icon = "ui://Emoji/" .. this.emotionDataList[index]
    obj.onClick:Clear()
    obj.onClick:Add(function()
        emotionCtrl.selectedIndex = 0;
        showEmotion = false;
        if string.lenUtf8(inputText.text) < 10 then
            --local str = "<img src='ui://CommonUI/img_biaoqing_%s'/>";
            --index = string.format(str,index + 1);
            --inputText.emojies
            local emojiName = logicMgr.ChatManager.GetEmojiName(index)
            inputText:ReplaceSelection(emojiName)
            --index = string.format("<sprite=%s>",index + 1);
            --inputText.text = inputText.text..index;
        end
    end);
end

function UIChatPanel.onClickReturn()
    logicMgr.ChatManager.refreshMsgRead(curPrivateData["roleId"]);
    this.onClickPrivate(true, true);
    curPrivateData = {};
end

function UIChatPanel.onCloseClick()
    pnlChannel.selectedIndex = 0;
    if isOpenUI(PanelNames.UICity) or isOpenUI(PanelNames.UIBattle) or isOpenUI(PanelNames.UIInvasionBattle) or isOpenUI(PanelNames.UIGuild) then
        if m_frame_mat then
            for i=0, m_frame_mat.Length - 1 do
                m_frame_mat:GetValue(i):SetFloat("_StencilComp", 8)
            end
            m_frame_mat = nil
        end
    end

    closeUI(PanelNames.UIChatPanel)
    closeUI(PanelNames.ChatHeadInfo)
end
function UIChatPanel.InitLBSServer()
    this.ctrlServer.selectedIndex = logicMgr.LBSManager.isSelectLBS and 0 or 1
    isCityInLBS = logicMgr.LBSManager.isSelectLBS
end
function UIChatPanel.RefreshServer()
    local index = this.ctrlServer.selectedIndex
    if index == 0 then
        currentChannel.visible = true
        isCityInLBS = true
    else
        currentChannel.visible = false
        isCityInLBS = false
    end
    --city
    if this.btnListCtrl.selectedIndex == 0 then
        if isCityInLBS then
            curChannel = Config.MsgChannel.LBS
        else
            if this.isInvasionTeam then
                curChannel=Config.MsgChannel.InvasionTeam
            else
                curChannel = Config.MsgChannel.Server
            end
        end
    end
    this.freshReceiveMsg(true)
end
function UIChatPanel.OnClickServer()
    this.RefreshServer()
end

function UIChatPanel.OnFocusOutInput()
    if IsWindowEditor() then
        return
    end
    if string.IsNilOrEmpty(this.inputText.text) then
        return
    end
    this.onClickSendMsg()
end
function UIChatPanel.appointChat(str)
    inputText.text = str;
end
function UIChatPanel.CityRoomJoinSuc()
    if this.needShowJoinRoomTip then
        UISysTips.AddMsg("频道加入成功")
        this.needShowJoinRoomTip = false
        logicMgr.ChatManager.ClearLBSMsg()
        this.freshReceiveMsg(true)
    end
end
function UIChatPanel.Fresh_ChatByMsg()
    this.freshReceiveMsg()
    local count = #msgInfo
    if count > 0 and this.refreshLastIndex >= count then
        this.ScrollToBottom()
    end

end

return UIChatPanel;













